﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccessLayer.Admin.Copy.UniversityStruct;
using System.Transactions;
using DataAccessLayer.Properties;
using IMModel.Domain;

namespace DataAccessLayer.Admin.Copy.Aggregation
{
    public class CopyUniversity
    {
        private ICopy departmentCopy = new DepartmentCopy();
        private ICopy respondentCopy = new RespondentCopy();

        public void CopyRespondent(int IDCopiedRespondent, int? IDParentDepartment, int fromIDTerm, int toIDTerm)
        {
            if (IDParentDepartment == null)
            {
                throw new ArgumentException("IDParentDepartment не может быть == NULL");
            }

            respondentCopy.Copy(IDCopiedRespondent, IDParentDepartment, fromIDTerm, toIDTerm);
        }

        public void StartCopyAll(int fromIDTerm, int toIDTerm)
        {
            using (IMModel.Domain.IMDataDataContext db = new IMModel.Domain.IMDataDataContext(Settings.Default.IndexMarkConnectionString))
            {
                using (var transaction = new TransactionScope())
                {
                    IEnumerable<DepartmentTerm> rootsDepartmentTerms = db.DepartmentTerms.Where(w => w.IDTerm == fromIDTerm
                        && w.IDParentDepartmentTerm == null);
                    foreach (DepartmentTerm dt in rootsDepartmentTerms)
                    {
                        this.HierarchicalCopyDepartment(dt.IDDepartmentTerm, null, fromIDTerm, toIDTerm);
                    }

                    transaction.Complete();
                }
            }
        }

        public void HierarchicalCopyDepartment(int oldIDDepartmentTerm, int? toIDParentDepartmentTerm, int fromIDTerm, int toIDTerm)
        {
            using (IMModel.Domain.IMDataDataContext db = new IMModel.Domain.IMDataDataContext(Settings.Default.IndexMarkConnectionString))
            {
                using (var transaction = new TransactionScope())
                {
                    int newIDDepartmentTerm = departmentCopy.Copy(oldIDDepartmentTerm, toIDParentDepartmentTerm, fromIDTerm, toIDTerm);

                    foreach (DepartmentTerm dt in db.DepartmentTerms.Where(w => w.IDParentDepartmentTerm == oldIDDepartmentTerm
                        && w.IDTerm == fromIDTerm))
                    {
                        HierarchicalCopyDepartment(dt.IDDepartmentTerm, newIDDepartmentTerm, fromIDTerm, toIDTerm);
                    }

                    foreach (Respondent resp in db.Respondents.Where(w => w.IDDepartmentTerm == oldIDDepartmentTerm))
                    {
                        respondentCopy.Copy(resp.IDRespondent, newIDDepartmentTerm, fromIDTerm, toIDTerm);
                    }

                    transaction.Complete();
                }
            }
        }
    }
}
